#!/usr/bin/env bash

set -eo pipefail

NATIVE_IMAGE=`which native-image` || true

if [ -z "$NATIVE_IMAGE" ]; then
  if [ -z "$GRAALVM_HOME" ]; then
      echo "Please set GRAALVM_HOME"
      exit 1
  fi

  "$GRAALVM_HOME/bin/gu" install native-image || true

  NATIVE_IMAGE="$GRAALVM_HOME/bin/native-image"
fi

export __CLOSH_USE_SCI_EVAL__=true

use_lein=false # set to true to build uberjar with project.clj instead of boot

if [ $use_lein = true ]; then
    npm run compile-sci-lein
    jar=target/closh-sci-0.0.1-SNAPSHOT-standalone.jar
else
    npm run compile-sci-boot
    jar=target/closh-zero-sci.jar
fi


$NATIVE_IMAGE \
  -jar "$jar" \
  -H:Name=closh-zero-sci \
  -H:+ReportExceptionStackTraces \
  -J-Dclojure.spec.skip-macros=true \
  -J-Dclojure.compiler.direct-linking=true \
  "-H:IncludeResources=CLOSH_VERSION" \
  -H:ReflectionConfigurationFiles=reflection.json \
  --initialize-at-run-time=java.lang.Math\$RandomNumberGeneratorHolder \
  --initialize-at-build-time \
  -H:Log=registerResource: \
  -H:EnableURLProtocols=http,https \
  --enable-all-security-services \
  -H:+JNI \
  --verbose \
  --no-fallback \
  --no-server \
  --report-unsupported-elements-at-runtime \
  -H:+TraceClassInitialization \
  -H:+PrintClassInitialization \
  "-J-Xmx8g"
